<?php


class ApplicationController
{
	static public function process($defaultcontroller)
	{
		$params = array_merge($_GET, $_POST);

		// If there is no controller, assume default controller. If 
		// there is no action, assume index action
		if(!array_key_exists('controller', $params))
			$params['controller'] = $defaultcontroller;
		if(!array_key_exists('action', $params))
			$params['action'] = 'index';

		$controller = $params['controller'];
		$action = $params['action'];

		$classname =  $controller . "Controller";
		$filename = "controllers/" . $classname . ".php";
		if(!file_exists($filename))
			die('No such controller');

		require_once("controllers/Controller.php");
		require_once($filename);

		$c = new ReflectionClass($classname);

		try
		{
			$m = $c->getMethod($action);
		}
		catch(Exception $e)
		{
			die('No such method');				
		}

		$obj = new $classname();
		if($obj->wantsRawData($action))
		{
			unset($_GET['controller']);
			unset($_GET['action']);
			$obj->setRawData($params, $_GET, $_POST);

			unset($_GET);
			unset($_POST);

			call_user_func_array(array($obj, $action),
				array());
		}
		else
		{
			// Send data as parameters
			$callparams = array();
			foreach($m->getParameters() as $reflparam)
			{
				if(!array_key_exists($reflparam->getName(), $params))
					die('Parameter that is\'t there is required');
				array_push($callparams, $params[$reflparam->getName()]);
			}

			unset($_GET);
			unset($_POST);

			call_user_func_array(array($obj, $action),
				$callparams);
		}
	}

	/**
	 * Call this function like this: 
	 * ApplicationController::buildUrl('Main', 'someAction', 
	 * 		'paramname1', 'value for that param',
	 * 		'paramname2', 155155);
	 *
	 * For example, let's say you have CalendarController and a "feed" 
	 * action that takes 1 parameter named "id". To view feed with id 5 
	 * you would call
	 *
	 * ApplicationController::buildUrl('Calendar', 'feed', 
	 * 		'id', 5);
	 */
	static function buildUrl($controller, $action)
	{
		$url = "index.php?controller={$controller}" .
			"&action={$action}";

		// TODO: URL encoding...
		$allArgs = func_get_args();
		$params = array_slice($allArgs, 2);

		if(count($params) > 0)
		{
			if(count($params) % 2 != 0)
				throw new Exception("Uneven number of args!?!");

			for($i = 0; $i < count($params); $i++)
			{
				if($i % 2 == 0)
					$url .= "&" . $params[$i];
				else
					$url .= "=" . $params[$i];
			}
		}

		return $url;
	}

	static function buildAbsUrl($controller, $action, $params = array())
	{
		require('config/config.php');
		$url = $_CONFIG['absurl'] . 
				self::buildUrl($controller, $action, $params);
		return $url;
		
	}

			

}


?>
